package cn.edu.sig.controller;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import cn.edu.sig.bean.CurrentPage;
import cn.edu.sig.bean.Goods;
import cn.edu.sig.bean.History;
import cn.edu.sig.bean.User;
import cn.edu.sig.service.GoodsService;
import cn.edu.sig.service.HistoryService;

@Controller
public class HistoryController {

	@Resource(name = "goodsService")
	private GoodsService goodsService;

	@Resource(name = "historyService")
	private HistoryService historyService;

	@RequestMapping(value = "cancel.html", method = RequestMethod.GET)
	public String canclePage(
			@ModelAttribute(value = "code") User user,
			@RequestParam(value = "status", required = true) int status,
			Model model) {
		Goods goods = new Goods();

		goods.setUser(user);

		List<Goods> goodsList = goodsService.findByStatu(user, status);

		model.addAttribute("goodsList", goodsList);

		return "/common/cancel";
	}

	@RequestMapping(value = "addHistory.action", method = RequestMethod.POST)
	public String addHistory(
			@ModelAttribute(value = "history") History history, 
			Model model) {

		Date createTime = new Date();
		history.setCreateTime(createTime);
		historyService.addHistory(history);
		goodsService.updateGoods(history.getGoods());
		model.addAttribute("user", history.getUser());

		return "redirect:historyList.html?code=" + history.getUser().getCode()
				+ "&pageNumber=1";
	}

	@RequestMapping(value = "historyList.html", method = RequestMethod.GET)
	public String historyList(
			@ModelAttribute(value = "code") User user,
			@RequestParam(value = "pageNumber", required = true) Integer pageNo,
			Model model) {

		CurrentPage<History> list = historyService.findAllByUser(user, pageNo,
				5);
		model.addAttribute("list", list);
		model.addAttribute("user", user);
		return "history";
	}
}
